package com.googlecode.lohr.tools.interpreter;

import lohr.lang.dom.IdentifierName;
import lohr.lang.dom.MethodInvocation;
import lohr.lang.dom.ReferenceExpression;

/**
 * Implementation of an expression that invokes a method.
 * Also known as a call site.
 */
public class MethodInvocationImpl extends ExpressionImpl {
	
	MethodImpl _method;
	ReferenceExpressionImpl _reference;
	
	
	public MethodInvocationImpl(LohrInterpreter interpreter, MethodInvocation invocation) {
		super(interpreter, invocation);
		ReferenceExpression referenceExpression= invocation.getTarget();
		if (referenceExpression != null) 
			_reference= new ReferenceExpressionImpl(interpreter, referenceExpression);
		
		// lookup the method to be invoked
		IdentifierName methodIdentifier= interpreter.resolve(invocation.getMethodIdentifier());
		_method= interpreter.getRespository().findByIdentifier(methodIdentifier);
		if (_method == null)
			throw new RuntimeException("Method not found: "+methodIdentifier);
	}

	@Override
	public ObjectImpl invoke(ObjectImpl invocationContext, Locals arguments) {
		ObjectImpl target= invocationContext;
		if (_reference != null)
			target= _reference.invoke(invocationContext, arguments);
		return _method.invoke(target, arguments);
	}

}
